"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

import sys
from PyQt4 import QtGui
from msnp.gui.widgets.SettingsWidget import SettingsWidget
from msnp.gui.widgets.GroupWidget import GroupWidget
from msnp.gui.widgets.StartWidget import StartWidget
from msnp.gui.widgets.GroupCollectionWidget import GroupCollectionWidget
from msnp.gui import GUIHelper
from msnp.gui.widgets.AudioWidget import AudioWidget
from msnp.logger import Logger
from msnp.gui.widgets.MessageWidget import MessageWidget
from msnp.gui.widgets.ProgressBarWidget import ProgressBarWidget
from msnp.gui.widgets.PersonalMessageWidget import PersonalMessageWidget
from msnp.persistence import PersistenceController, XMLController
from msnp.gui.widgets.DBErrorWidget import DBErrorWidget
from msnp.service import network
from msnp.gui.widgets.SystemTray import SystemTray
from msnp.gui.widgets.ConfirmWidget import ConfirmWidget

app = QtGui.QApplication(sys.argv)
#mainWidget = None
startWidget = None
groupCollectionWidget = None
settingsWidget = None
groupWidget = None
audioTableWidget = None
messageWidget = None
progressBar = None
dbErrorWidget = None
pMessageWidgets = {}
systemTray = None
confirmWidget = None

__isGUI = True


def stopGUI():
    """This function exits the application by exiting the graphical user interface (calls app.exit())."""
    global __isGUI
    if __isGUI:
        app.exit()

##################
## OPEN WIDGETS ##
##################

def startGUI():
    """This function starts the graphical user interface by opening the start widget."""
    global __isGUI
    if __isGUI:
        openStartWidget()
        sys.exit(app.exec_())

def openStartWidget():
    """This function creates a StartWidget object and displays it."""
    global startWidget
    global __isGUI
    if __isGUI:
        startWidget = StartWidget()
        startWidget.buildLoginWidget()
        startWidget.show()

def openSystemTray():
    """This function creates a SystemTray object and displays it."""
    global systemTray
    global __isGUI
    if __isGUI:
        systemTray = SystemTray()
        systemTray.show()

def openGroupCollection(groups):
    """This function creates a GroupCollectionWidget object and displays it."""
    global groupCollectionWidget
    global __isGUI
    if __isGUI:
        groupCollectionWidget = GroupCollectionWidget(groups)
        groupCollectionWidget.show()
    
def openSettings(parent, synchPossible):
    """This function creates a SettingsWidget object and displays it (eventually closes an already opened SettingsWidget object)."""
    global settingsWidget
    global __isGUI
    if __isGUI:
        if settingsWidget != None:
            settingsWidget.destroy()
        Logger.guiInfo('try to open settings')
        settingsWidget = SettingsWidget(synchPossible, parent)
        settingsWidget.show()
    
#if group None open search, else open group splash...
def openGroupWidget(parent, isSearch=True, groupDetailType=GUIHelper.GroupDetailType.NOT_MEMBER):
    """This function creates a GroupWidget object and displays it (eventually closes an already opened GroupWidget object)."""
    global groupWidget
    global __isGUI
    if __isGUI:
        if groupWidget != None:
            groupWidget.destroy()
        groupWidget = GroupWidget(parent)
        if isSearch:
            groupWidget.buildSearchWidget()
        elif groupDetailType != None and groupDetailType == GUIHelper.GroupDetailType.NEW_GROUP:
            groupWidget.buildGroupDetailWidget(groupDetailType, None)
        else:
            groupWidget.buildGroupSplashWidget()
        groupWidget.show()
    
def openAudioList(parent):
    """This function creates an AudioWidget object and displays it (eventually closes an already opened AudioWidget object)."""
    global audioTableWidget
    global __isGUI
    if __isGUI:
        if audioTableWidget != None:
            audioTableWidget.destroy()
        audioTableWidget = AudioWidget(parent) 
        audioTableWidget.buildAudioSplashWidget()
        audioTableWidget.show()

def openMessageWidget(parent, isSplash=True):
    """This function creates a MessageWidget object and displays it (eventually closes an already opened MessageWidget object)."""
    global messageWidget
    global __isGUI
    if __isGUI:
        if messageWidget != None:
            messageWidget.destroy()
        messageWidget = MessageWidget(parent)
        if isSplash:
            messageWidget.buildMessageSplashWidget()
            messageWidget.show()
            network.NetworkController.getStoredMessages()
        else:
            messageWidget.buildMessageWidget()
            messageWidget.show()
    
def openProgressBar(max, isModal):
    """This function creates a ProgressBarWidget object and displays it."""
    global progressBar
    global __isGUI
    if __isGUI:
        progressBar = ProgressBarWidget(max, isModal)
        progressBar.show()
    
def openPersonalMessageWidget(chatPartnerName):
    """This function creates a PersonalMessageWidget object, if there does not already exist one for the given chatPartnerName, and displays it."""
    global pMessageWidgets
    global __isGUI
    if __isGUI:
        tmpWidget = getPersonalMessageWidget(chatPartnerName)
        if tmpWidget == None:
            settings = XMLController.readAllSettings()
            username = settings.getCurrentUserSettings().getUsername()
            chatMessages = PersistenceController.selectChatHistoryByPartnernameAndUsername(chatPartnerName, username)
            pMessageWidget = PersonalMessageWidget(chatPartnerName, chatMessages)
            pMessageWidget.show()
            pMessageWidgets[chatPartnerName] = pMessageWidget
        else:
            print 'personal message widget for ' + chatPartnerName + ' already open'
            tmpWidget.setVisible(True)

def openConfirmWidget():
    """This function creates a ConfirmWidget object and displays it (eventually closes an already opened ConfirmWidget object)."""
    global confirmWidget
    global __isGUI
    if __isGUI:
        if confirmWidget != None:
            confirmWidget.destroy()
        confirmWidget = ConfirmWidget()
        confirmWidget.buildConfirmSplashWidget()
        confirmWidget.show()
        
def openDBErrorWidget(dbType, errorType, traceback):
    """This function creates a DBErrorWidget object and displays it."""
    global dbErrorWidget
    global groupCollectionWidget
    global startWidget
    global __isGUI
    if __isGUI:
        if dbErrorWidget == None:
            parent = startWidget
            if groupCollectionWidget != None:
                parent = groupCollectionWidget
            dbErrorWidget = DBErrorWidget(dbType, errorType, traceback, parent)
            dbErrorWidget.show()
        else:
            dbErrorWidget.setVisible(True)

#################
## GET WIDGETS ##
#################

def getPersonalMessageWidget(chatPartnerName):
    """This function returns the PersonalMessageWidget object belonging to the given chatPartnerName or None if there does not exist such an object."""
    global pMessageWidgets
    global __isGUI
    if __isGUI:
        for (partnerName, widget) in pMessageWidgets.items():
            if partnerName == chatPartnerName:
                return widget
    return None

def getPersonalMessageWidgets():
    """This function returns all existing PersonalMessageWidget objects stored in pMessageWidgets."""
    global pMessageWidgets
    global __isGUI
    if __isGUI:
        return pMessageWidgets
    return None

def getGroupWidget():
    """This function returns the GroupWidget object groupWidget."""
    global groupWidget
    global __isGUI
    if __isGUI:
        return groupWidget
    return None

def getGroupCollectionWidget():
    """This function returns the GroupCollectionWidget object groupWidget."""
    global groupCollectionWidget
    global __isGUI
    if __isGUI:
        return groupCollectionWidget
    return None

def getStartWidget():
    """This function returns the StartWidget object startWidget."""
    global startWidget
    global __isGUI
    if __isGUI:
        return startWidget
    return None

def getSettingsWidget():
    """This function returns the SettingsWidget object settingsWidget."""
    global settingsWidget
    global __isGUI
    if __isGUI:
        return settingsWidget
    return None

def getProgressBar():
    """This function returns the ProgressBar object progressBar."""
    global progressBar
    global __isGUI
    if __isGUI:
        return progressBar
    return None

def getMessageWidget():
    """This function returns the MessageWidget object messageWidget."""
    global messageWidget
    global __isGUI
    if __isGUI:
        return messageWidget
    return None

def getAudioTableWidget():
    """This function returns the AudioWidget object audiotableWidget."""
    global audioTableWidget
    global __isGUI
    if __isGUI:
        return audioTableWidget
    return None

def getSystemTray():
    """This function returns the SystemTray object systemTray."""
    global systemTray
    global __isGUI
    if __isGUI:
        return systemTray
    return None

def getConfirmWidget():
    """This function returns the ConfirmWidget object confirmWidget."""
    global confirmWidget
    global __isGUI
    if __isGUI:
        return confirmWidget
    return None

###################
## CLOSE WIDGETS ##
###################

def closeStartWidget():
    """This function closes the StartWidget object startWidget."""
    global startWidget
    global __isGUI
    if __isGUI:
        if startWidget != None:
            startWidget.close()
        startWidget = None
    
def closeSettingsWidget():
    """This function closes the SettingsWidget object settingsWidget."""
    global settingsWidget
    global __isGUI
    if __isGUI:
        if settingsWidget != None:
            settingsWidget.close()
        settingsWidget = None

def closeGroupWidget():
    """This function closes the GroupWidget object groupWidget."""
    global groupWidget
    global __isGUI
    if __isGUI:
        if groupWidget != None:
            groupWidget.close()
        groupWidget = None

def closeGroupCollectionWidget():
    """This function closes the GroupCollectionWidget object groupCollectionWidget."""
    global groupCollectionWidget
    global __isGUI
    if __isGUI:
        if groupCollectionWidget != None:
            groupCollectionWidget.close()
        groupCollectionWidget = None
    
def closeAudioTableWidget():
    """This function closes the AudioWidget object audioTableWidget."""
    global audioTableWidget
    global __isGUI
    if __isGUI:
        if audioTableWidget != None:
            audioTableWidget.close()
        audioTableWidget = None
    
def closeMessageWidget():
    """This function closes the MessageWidget object messageWidget."""
    global messageWidget
    global __isGUI
    if __isGUI:
        if messageWidget != None:
            messageWidget.close()
        messageWidget = None
    
def closeProgressBar():
    """This function closes the ProgressBar object progressBar."""
    global progressBar
    global __isGUI
    if __isGUI:
        if progressBar != None:
            progressBar.close()
        progressBar = None
    
def closePersonalMessageWidget(chatPartnerName):
    """This function closes the PersonalMessageWidget object that belongs to the given chatPartnerName."""
    global pMessageWidgets
    global __isGUI
    if __isGUI:
        pMessageWidgets[chatPartnerName] = None
    
def closeConfirmWidget():
    """This function closes the ConfirmWidget object confirmWidget."""
    global confirmWidget
    global __isGUI
    if __isGUI:
        if confirmWidget != None:
            confirmWidget.close()
        confirmWidget = None

def closeWidgets():
    """This function closes all widgets."""
    global groupCollectionWidget
    global settingsWidget
    global groupWidget
    global audioTableWidget
    global messageWidget
    global progressBar
    global pMessageWidgets
    global confirmWidget
    global __isGUI
    if __isGUI:
        closeGroupCollectionWidget()
        closeSettingsWidget()
        closeGroupWidget()
        closeAudioTableWidget()
        closeMessageWidget()
        closeProgressBar()
        if pMessageWidgets != None:
            for widget in pMessageWidgets.itervalues():
                if widget != None:
                    widget.close()
            pMessageWidgets = {}
        closeConfirmWidget()
    #    setWidgetsVisible(False)
            
def setWidgetsVisible(visibility):
    """This function sets the visibility of all widgets to the given value."""
    global groupCollectionWidget
    global settingsWidget
    global groupWidget
    global audioTableWidget
    global messageWidget
    global progressBar
    global pMessageWidgets
    global confirmWidget
    global __isGUI
    if __isGUI:
        if groupCollectionWidget != None:
            groupCollectionWidget.setVisible(visibility)
        if settingsWidget != None:
            settingsWidget.setVisible(visibility)
        if groupWidget != None:
            groupWidget.setVisible(visibility)
        if audioTableWidget != None:
            audioTableWidget.setVisible(visibility)
        if messageWidget != None:
            messageWidget.setVisible(visibility)
        if progressBar != None:
            progressBar.setVisible(visibility)
        if pMessageWidgets != None:
            for widget in pMessageWidgets.itervalues():
                if widget != None:
                    widget.setVisible(visibility)
        if confirmWidget != None:
            confirmWidget.setVisible(visibility)
            
def resetDBErrorWidget():
    """This function closes the DBErrorWidget object dbErrorWidget."""
    global dbErrorWidget
    global __isGUI
    if __isGUI:
        dbErrorWidget = None
        
##############
## GUI-flag ##
##############

def isGUI():
    """This function returns __isGUI."""
    global __isGUI
    return __isGUI

def disableGUI():
    """This function sets the value of __isGUI to False."""
    global __isGUI
    __isGUI = False
